import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'data_loader.dart';
import 'detail_play.dart';

class VodRelatedView extends StatefulWidget {
  final Map<String, dynamic> data;
  final int tid;

  VodRelatedView({required this.data, required this.tid});

  @override
  State createState() => _VodRelatedViewState();
}

class _VodRelatedViewState extends State<VodRelatedView> {
  bool isFocused = false;
  int related_index = -1;
  final DataLoader dataLoader = DataLoader();
  late Future<List<Map<String, dynamic>>?> _related;

  @override
  void initState() {
    _related = dataLoader.loadRecommendation(tid: widget.tid);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Map<String, dynamic>>?>(
      future: _related,
      builder: (BuildContext context,
          AsyncSnapshot<List<Map<String, dynamic>>?> snapshot) {
        if (snapshot.connectionState == ConnectionState.done &&
            snapshot.hasData) {
          List<Map<String, dynamic>> data = snapshot.data!;
          int rowIndex = (data.length) ~/ 3;
          List<Row> columns = [];
          for (var i = 0; i <= rowIndex; i++) {
            List<Widget> rows = [];
            for (var j = 0; j < 3; j++) {
              int index = i * 3 + j;
              if (data.length == index) {
                break;
              }
              Color color = _gradientColor(index);
              rows.add(
                  Expanded(child: focusRelated(data[index], index, color)));
            }
            columns.add(Row(children: rows));
          }
          return Column(children: columns);
        } else {
          return Container(
            color: Colors.white,
            constraints: const BoxConstraints.expand(),
            child: const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
              ),
            ),
          );
          ;
        }
      },
    );
  }

  Widget focusRelated(Map<String, dynamic> data, int index, Color color) {
    return Focus(
      onKey: (FocusNode node, RawKeyEvent event) {
        if (event.logicalKey == LogicalKeyboardKey.select) {
          Navigator.pushAndRemoveUntil(
            context,
            MaterialPageRoute(
                builder: (context) =>
                    DetailPlay(vid: data['vod_id'], tid: widget.tid)),
            (route) => false,
          );
          return KeyEventResult.handled;
        }
        return KeyEventResult.ignored;
      },
      onFocusChange: (focused) => setState(() {
        related_index = focused ? index : -1;
        print('=========== related_index ${related_index}');
      }),
      child: Container(
        height: 210,
        decoration: BoxDecoration(
          border: Border.all(
            color:
                related_index == index ? Colors.deepOrange : Colors.transparent,
            width: 3,
            style: BorderStyle.solid,
          ),
        ),
        child: Card(
          elevation: 5,
          margin: EdgeInsets.all(0),
          color: color,
          child: Stack(
            alignment: Alignment.bottomLeft,
            children: <Widget>[
              ClipRRect(
                child: Image.network(
                  data['vod_pic'].toString(),
                  fit: BoxFit.cover,
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height,
                ),
                borderRadius: BorderRadius.all(Radius.circular(5)),
              ),
              Container(
                width: MediaQuery.of(context).size.width,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      data['vod_name'].toString(),
                      style: TextStyle(color: Colors.white, fontSize: 15),
                    ),
                    Text(
                      overflow: TextOverflow.ellipsis,
                      maxLines: 2,
                      data['vod_blurb'].toString().replaceAll('&amp;nbsp;', ''),
                      style: TextStyle(color: Colors.white, fontSize: 12),
                    ),
                  ],
                ),
                color: color.withAlpha(240),
                padding: EdgeInsets.all(0),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Color _gradientColor(int index) {
    int rowIndex = index ~/ 3;
    int colIndex = index % 3;

    Color color;
    if ((rowIndex + colIndex) % 3 == 0) {
      color = Colors.red;
    } else if ((rowIndex + colIndex) % 3 == 1) {
      color = Colors.orange;
    } else {
      color = Colors.green;
    }
    return color;
  }
}
